package com.topisv.tms.web.focus;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@Controller
@RequestMapping(value = "/focusExportBackupTask")
public class FocusExportBackupTaskController {
	private static final Logger log = LoggerFactory.getLogger(FocusExportBackupTaskController.class);
	
	private final String url = "work/gather/exprotExcel";

	private final int pageSize = 40;

	@Autowired
	private CustomersService customersService;
	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;

	@RequestMapping(value = "init")
	public String init(Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customers = customersService.loadCustomerByAuthority(user);
		RestCustomersAreagroupVo restCustomersAreagroupVo = null;
		try {
			restCustomersAreagroupVo = customerAreaGroupService.getRestCustomersAreagroupVo(customers.get(0).getCustomerCode());
		} catch (Exception e) {
			log.error("/exportBackupTask/init" + e);
			
		}
		model.addAttribute("status", 0);
		model.addAttribute("customers", customers);
		model.addAttribute("object", restCustomersAreagroupVo);
		return url;
	}

	@RequestMapping(value = "pageBackupTask")
	public String list(
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			Model model, ServletRequest request) {
		Date fromDate = null;
		Date endDate = null;
		Page<BackupTask> pageBackupTasks = null;
		ShiroUser user = getShiroUser();
		try {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
			String from = (String) searchParams.get("EQ_fromDate");
			String end = (String) searchParams.get("EQ_endDate");

			searchParams.remove("EQ_fromDate");
			searchParams.remove("EQ_endDate");

			if (from.length() > 10) {
				fromDate = TimeUtil.getDateMMSS(from);
			} else {
				fromDate = TimeUtil.getDate(from);
			}
			if (end.length() > 10) {
				endDate = TimeUtil.getDateMMSS(end);
			} else {
				endDate = TimeUtil.getDate(end);
			}
			// fromDate = TopIsvDateUtils.addHours(fromDate, -14);//起始时间
			// endDate = TopIsvDateUtils.addHours(endDate, -14);//终止时间
			pageBackupTasks = backupTaskService.getPageBackupTasks(searchParams, pageNumber, pageSize, sortType, fromDate,endDate);
			List<Customers> customers = customersService.loadCustomerByAuthority(user);
			RestCustomersAreagroupVo restCustomersAreagroupVo = null;
			try {
				restCustomersAreagroupVo = customerAreaGroupService.getRestCustomersAreagroupVo(customers.get(0).getCustomerCode());// HttpPost.getRestCustomersAreagroupVo(customers.get(0));//
													// 设置网点信息
			} catch (Exception e) {
				log.error("/exportBackupTask/init" + e);
				
			}
			searchParams.put("EQ_fromDate", from);
			searchParams.put("EQ_endDate", end);
			model.addAttribute("customers", customers);
			model.addAttribute("object", restCustomersAreagroupVo);
			model.addAttribute("status", 1);
			model.addAttribute("pageBackupTasks", pageBackupTasks);
			model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return url;

	}

	/**
	 * 导出明细
	 */
	@RequestMapping(value = "exportExcel")
	public String exportExcel(Model model, ServletRequest request,
			HttpServletResponse response) {
		Date fromDate = null;
		Date endDate = null;
		List<BackupTask> listBackupTasks = null;
		try {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");

			String customerCode = (String) searchParams.get("customerCode");
			String areaGroupCode = (String) searchParams.get("areaGroupCode");
			String from = (String) searchParams.get("fromDate");
			String end = (String) searchParams.get("endDate");
			if (from.length() > 10) {
				fromDate = TimeUtil.getDateMMSS(from);
			} else {
				fromDate = TimeUtil.getDate(from);
			}
			if (end.length() > 10) {
				endDate = TimeUtil.getDateMMSS(end);
			} else {
				endDate = TimeUtil.getDate(end);
			}
			searchParams.remove("fromDate");
			searchParams.remove("endDate");
			searchParams.remove("customerCode");
			searchParams.remove("areaGroupCode");
			searchParams.put("EQ_customerCode", customerCode);
			searchParams.put("EQ_areaGroupCode", areaGroupCode);
			listBackupTasks = backupTaskService.getListBackupTasks(searchParams, fromDate, endDate);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment; filename="+ customerCode + "_" + areaGroupCode + ".xls");
			WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
			WritableSheet sheet = book.createSheet("第一页", 0);

			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			int length = listBackupTasks.size();

			sheet.addCell(new Label(0, 0, areaGroupCode + "  共计："+ Integer.toString(length) + " 出库批次", wcf_center));

			sheet.setColumnView(0, 22);// sku
			sheet.setColumnView(1, 15);// 货号
			sheet.setColumnView(2, 22);// 数量
			sheet.setColumnView(3, 15);// 名称
			sheet.setColumnView(4, 15);// 规格

			sheet.addCell(new Label(0, 1, "SKU"));
			sheet.addCell(new Label(1, 1, "货号"));
			sheet.addCell(new Label(2, 1, "数量"));
			sheet.addCell(new Label(3, 1, "名称"));
			sheet.addCell(new Label(4, 1, "规格"));
			Map<String, Integer> maps = backupTaskService.getBackupTaskSku(listBackupTasks);
			int i = 0;
			for (String key : maps.keySet()) {
				EdiGoodsSku ediGoodsSku = ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, key);
				if (ediGoodsSku != null) {
					sheet.addCell(new Label(1, i + 2, ediGoodsSku.getBar()));// 货号
					sheet.addCell(new Label(3, i + 2, ediGoodsSku.getSkuName()));// 名称
					sheet.addCell(new Label(4, i + 2, ediGoodsSku.getSiz()));// 规格
				}
				sheet.addCell(new Label(0, i + 2, key));// sku
				sheet.addCell(new Label(2, i + 2, maps.get(key) + ""));// 数量
				i++;
			}
			book.write();
			book.close();
		} catch (Exception e) {
			
		}
		return null;
	}

	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

}
